import { reqLogin, reqGetUserInfo, reqGetUserAvatar } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login({ commit }, data) {
    const res = await reqLogin(data)
    commit('setToken', res.data)
    // return res
  },
  async getUserInfo({ commit }) {
    const { data: res1 } = await reqGetUserInfo()
    const { data: res2 } = await reqGetUserAvatar(res1.userId)
    const result = { ...res1, ...res2 }
    commit('setUserInfo', result)
    return result
  },
  logout({ commit }) {
    resetRouter()
    commit('permission/setRoutes', [], { root: true })
    commit('removeToken')
    commit('removeUserInfo')
  }
}
const getters = {}
export default {
  namespaced: true,
  state, mutations, actions, getters
}
